﻿Imports ADOEntity
Imports System.Data
Partial Class Administrator_DepartmentList
    Inherits Web.UI.BasePage
    Private Const strMenuCode As String = "M64"
    Dim sDeptEntity As userEntities
    Dim dsDepartment As New DataSet
    Dim clsQuery As clsDatabase
    Dim clsDataTable As New clsLINQToDataTable
    Dim intBeforeItemIndex As Integer
    Dim clsSessionMenuRight As clsSessionMenuRight = New clsSessionMenuRight
    Dim strMsg As String = ""

#Region " Even Page "

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        lblDeptCode.Text = Resources.resDepartment.deptCode & " : "
        lblDeptName.Text = Resources.resDepartment.deptName & " : "

        btnSearch.Text = Resources.resButton.btnSearch
        btnAdd.Text = Resources.resButton.btnAdd
        btnModify.Text = Resources.resButton.btnModify
        btnDelete.Text = Resources.resButton.btnDelete
        btnClear.Text = Resources.resButton.btnClear
        btnPrint.Text = Resources.resButton.btnPrint

        lblMsg.Text = Resources.resMessageAlert.alertEmptyGrid
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Try
            chkIsLogin()
            clsSessionMenuRight = Session("clsMenuRight")

            If (Not IsPostBack) Then
                setUserRightButton()
                CreateControlMP()
                setButton(1)
            Else
                dsDepartment = Session("dsTblMaster")
                gvDepartment.DataSource = dsDepartment.Tables("sDepartment")
                gvDepartment.DataBind()
            End If
        Catch ex As Exception

        End Try


    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Session("dsTblMaster") = dsDepartment
    End Sub

#End Region

#Region "SetForm"

    Sub CreateControlMP()

        Dim lblForm As Label = CType(Master.FindControl("lblForm"), Label)
        lblForm.Text = "ฝ่ายงาน"
    End Sub

#End Region

#Region " Even Button "

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        IsDataBind()
        clearGvIndex()
        SaveLogSearch()
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
        ' Response.Redirect("Department.aspx?Status=Add")

        Try
            If chkBeforeSave() Then
                sDeptEntity = New userEntities
                Dim sDepartment As New SDEPARTMENT

                sDepartment.DEPTCODE = txtDeptCode.Text
                sDepartment.DEPTNAME = txtDeptName.Text

                sDeptEntity.AddToSDEPARTMENT(sDepartment)
                sDeptEntity.SaveChanges()

                SaveLogNew()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)

            End If
        Catch ex As System.Data.UpdateException

            Dim codeError() As String = ex.InnerException.Message.Split(":")
            If codeError(0) = "ORA-00001" Then
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถเพิ่มได้ เนื่องจากรหัสนี้มีการนำมาใช้ในระบบแล้ว')", True)
            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            End If
            WriteError(ex, "btnAdd_Click", "DepartmentList")
        Catch ex As Exception
            WriteError(ex, "btnAdd_Click", "DepartmentList")
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)

        End Try
    End Sub

    Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnModify.Click
        'If Not (gvDepartment.SelectedIndex = -1) Then
        '    Response.Redirect("Department.aspx?Status=Edit&strDeptCode=" + gvDepartment.Rows(gvDepartment.SelectedIndex).Cells(1).Text)
        'Else
        '    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGrid + "')", True)
        'End If


        Try
            If chkBeforeSave() Then
                sDeptEntity = New userEntities
                Dim sDepartment As New SDEPARTMENT

                Dim qry = (From dept In sDeptEntity.SDEPARTMENT Where dept.DEPTCODE = txtDeptCode.Text).ToList
                'txtPoscode.Text = qry(0).POSCODE
                qry(0).DEPTNAME = txtDeptName.Text
                sDeptEntity.SaveChanges()

                SaveLogEdit()

                IsDataBind()
                reset()

                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resMsgKYC.msgSave + "')", True)

            Else
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + strMsg + "')", True)
            End If

        Catch ex As System.Data.UpdateException
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
            WriteError(ex, "btnModify_Click", "DepartmentList")
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('บันทึกผิดพลาด')", True)
            WriteError(ex, "btnModify_Click", "DepartmentList")
        End Try


    End Sub

    Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If Not (gvDepartment.SelectedIndex = -1) Then
            Dim DepC As String = gvDepartment.Rows(gvDepartment.SelectedIndex).Cells(1).Text
            Try
                sDeptEntity = New userEntities
                Dim qry = (From s_Dep In sDeptEntity.SDEPARTMENT Where s_Dep.DEPTCODE = DepC).ToList
                sDeptEntity.DeleteObject(qry(0))
                sDeptEntity.SaveChanges()

                SaveLogDelete(DepC)

                IsDataBind()
                reset()

            Catch ex As System.Data.UpdateException
                Dim codeError() As String = ex.InnerException.Message.Split(":")
                If codeError(0) = "ORA-02292" Then
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('ไม่สามารถลบได้ เนื่องจากมีการนำมาใช้ในระบบแล้ว')", True)
                Else
                    ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + ex.InnerException.Message + "')", True)
                End If
                WriteError(ex, "btnDelete_Click", "DepartmentList")
            Catch ex As Exception
                ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resError.errorMessage + "')", True)
                WriteError(ex, "btnDelete_Click", "DepartmentList")
            End Try

        Else
            ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "clientScript", "alert('" + Resources.resValidate.nonSelectGridDelete + "')", True)

        End If

    End Sub

    Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
        clear()
    End Sub

    Protected Sub btnPrint_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Dim a As String = txtDeptName.Text.Trim
        Dim param As String = "{ 'rptType' : '4'," _
                              & "'deptCode' : '" & txtDeptCode.Text.Trim & "'," _
                              & "'deptName' : '" & a.ToString & "'}"
        ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType, "key", "OpenWindowWithPost('../Form/frmPrintRptMaster.aspx','width=730,height=345,left=100,top=100,resizable=yes,scrollbars=yes','Report', " + param + ");", True)

        SaveLogPrint()
    End Sub


#End Region

#Region "Even GridView"

    Protected Sub gvDepartment_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvDepartment.SelectedIndexChanged
        Try
            If (gvDepartment.SelectedIndex = intBeforeItemIndex) Then
                clearGvIndex()
                reset()

                btnModify.Text = "แก้ไข"
            Else
                btnModify.Text = "บันทึก"

                setButton(2)

                txtDeptCode.Text = gvDepartment.Rows(gvDepartment.SelectedIndex).Cells(1).Text
                txtDeptName.Text = gvDepartment.Rows(gvDepartment.SelectedIndex).Cells(2).Text

                btnDelete.Attributes.Add("onclick", "return confirm('" + String.Format(Resources.resValidate.confirmDelete, _
                           IIf(gvDepartment.SelectedIndex = -1, "", gvDepartment.Rows(gvDepartment.SelectedIndex).Cells(2).Text)) + "');")
            End If
        Catch ex As Exception
            WriteError(ex, "gvDepartment_SelectedIndexChanged", "DepartmentList")
        End Try


    End Sub
    Protected Sub gvDepartment_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles gvDepartment.SelectedIndexChanging
        intBeforeItemIndex = gvDepartment.SelectedIndex
    End Sub

    Protected Sub gvDepartment_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles gvDepartment.PageIndexChanging
        gvDepartment.PageIndex = e.NewPageIndex
        clearGvIndex()
        DataBind()
    End Sub

    Protected Sub gvDepartment_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvDepartment.Sorting
        Dim dt = TryCast(dsDepartment.Tables("sDepartment"), DataTable)

        If dt IsNot Nothing Then

            'Sort the data.
            dt.DefaultView.Sort = e.SortExpression & " " & GetSortDirection(e.SortExpression)
            gvDepartment.DataSource = dsDepartment.Tables("sDepartment")
            gvDepartment.DataBind()
            clearGvIndex()
        End If
    End Sub

#End Region

#Region " Function"

    Private Sub setUserRightButton()
        Dim col As New Collection
        col.Add(btnSearch, statusbtn.Query.ToString)
        col.Add(btnAdd, statusbtn.Add.ToString)
        col.Add(btnModify, statusbtn.Modify.ToString)
        col.Add(btnDelete, statusbtn.delete.ToString)
        col.Add(btnPrint, statusbtn.print.ToString)
        setBtnToUserRight(col, strMenuCode, clsSessionMenuRight.getDsMenuRight)

    End Sub
    Private Sub clearGvIndex()
        gvDepartment.SelectedIndex = -1
        '  btnDelete.Attributes.Clear()
    End Sub

    Private Sub IsDataBind()
        Try

       
        sDeptEntity = New userEntities

        If dsDepartment.Tables.Contains("sDepartment") Then
            dsDepartment.Tables.Clear()
        End If
        Dim qryDept = From Department In sDeptEntity.SDEPARTMENT
                        Order By Department.DEPTCODE
                    Select Department.DEPTCODE, Department.DEPTNAME

        If Not (txtDeptCode.Text = "") Then
            qryDept = qryDept.Where(Function(Dept) Dept.DEPTCODE.Contains(txtDeptCode.Text))
        End If

        If Not (txtDeptName.Text = "") Then
            qryDept = qryDept.Where(Function(Dept) Dept.DEPTNAME.Contains(txtDeptName.Text))
        End If

        dsDepartment.Tables.Add(clsDataTable.LINQToDataTable(qryDept, "sDepartment").Copy)

        If (qryDept.Count = 0) Then
            lblMsg.Visible = True
            lblTotal.Text = ""
        Else
            lblMsg.Visible = False
            lblTotal.Text = "จำนวนรายการทั้งหมด " + qryDept.Count.ToString + " รายการ "

        End If

        gvDepartment.DataSource = dsDepartment.Tables("sDepartment")
        gvDepartment.DataBind()

        clsDataTable = Nothing
        Catch ex As Exception
            WriteError(ex, "IsDataBind", "DepartmentList")

        End Try
    End Sub

    Private Function GetSortDirection(ByVal column As String) As String

        ' By default, set the sort direction to ascending.
        Dim sortDirection = "DESC"

        ' Retrieve the last column that was sorted.
        Dim sortExpression = TryCast(ViewState("SortExpression"), String)

        If sortExpression IsNot Nothing Then
            ' Check if the same column is being sorted.
            ' Otherwise, the default value can be returned.
            If sortExpression = column Then
                Dim lastDirection = TryCast(ViewState("SortDirection"), String)
                If lastDirection IsNot Nothing _
                  AndAlso lastDirection = "DESC" Then

                    sortDirection = "ASC"

                End If
            End If
        End If

        ' Save new values in ViewState.
        ViewState("SortDirection") = sortDirection
        ViewState("SortExpression") = column
        Return sortDirection
    End Function

    Private Sub setButton(ByVal button As Integer)

        If button = 1 Then 'unselect
            lblMsg.Visible = False

            btnModify.Enabled = False
            btnDelete.Enabled = False

            btnSearch.Enabled = True
            btnAdd.Enabled = True

            txtDeptCode.Enabled = True

        ElseIf button = 2 Then 'select

            btnSearch.Enabled = False
            btnAdd.Enabled = False

            btnModify.Enabled = True
            btnDelete.Enabled = True

            txtDeptCode.Enabled = False

        End If

    End Sub

    Private Sub clear()
        If (dsDepartment.Tables.Contains("sDepartment")) Then
            dsDepartment.Tables("sDepartment").Clear()
            gvDepartment.DataSource = dsDepartment.Tables("sDepartment")
            gvDepartment.DataBind()
        End If
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtDeptCode.Text = ""
        txtDeptName.Text = ""
        lblTotal.Text = ""
        btnModify.Text = "แก้ไข"
    End Sub

    Private Sub reset()
        'gvUserRight.DataSource = dsUserRight.Tables("sUserRight")
        'gvUserRight.DataBind()
        clearGvIndex()
        setButton(1)
        lblMsg.Visible = False
        txtDeptCode.Text = ""
        txtDeptName.Text = ""
    End Sub

    Private Function chkBeforeSave() As Boolean
        Dim result As Boolean = True
      
        If (txtDeptCode.Text = "") Then
            result = False
            strMsg = strMsg & "กรุณาระบุรหัสฝ่าย" & "\n"
        End If


        If (txtDeptName.Text = "") Then
            result = False
            strMsg = strMsg & lblDeptName.Text & " : " & "กรุณาระบุชื่อฝ่าย" & "\n"

        End If

        Return result

    End Function

    Private Sub SaveLogSearch()
        Try

            Dim desc As String = ""

            If Not (txtDeptCode.Text = "") Then
                desc += " รหัสฝ่ายงาน - " + txtDeptCode.Text
            End If

            If Not (txtDeptName.Text = "") Then
                desc += " ชื่อฝ่ายงาน - " + txtDeptName.Text
            End If


            If Not desc = "" Then
                desc = "ค้นหาข้อมูลฝ่ายงาน จาก " + desc
            Else
                desc = "ค้นหาทั้งหมด"
            End If

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 1, desc, "M64")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogPrint()
        Try

            Dim desc As String = "พิมพ์ข้อมูลฝ่ายงาน"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction("", clsSessionMenuRight.getUserName, 2, desc, "M64")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogNew()
        Try

            Dim desc As String = "บันทึก ข้อมูลฝ่ายงาน (รหัสฝ่ายงาน " + txtDeptCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtDeptCode.Text, clsSessionMenuRight.getUserName, 3, desc, "M64")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogEdit()
        Try

            Dim desc As String = "บันทึก แก้ไข ข้อมูลฝ่ายงาน (รหัสฝ่ายงาน " + txtDeptCode.Text + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(txtDeptCode.Text, clsSessionMenuRight.getUserName, 4, desc, "M64")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Private Sub SaveLogDelete(ByVal value As String)
        Try

            Dim desc As String = "ลบข้อมูลฝ่ายงาน (รหัสฝ่ายงาน " + value + ")"

            Dim clsLogTransaction As New clsLogTransaction
            clsLogTransaction.saveLogTransaction(value, clsSessionMenuRight.getUserName, 5, desc, "M64")
            clsLogTransaction = Nothing
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

#End Region


End Class
